package com.pengpeng.flash.filter;

import com.alibaba.fastjson.JSON;
import com.pengpeng.flash.common.BaseContext;
import com.pengpeng.flash.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的uri
        String uri = request.getRequestURI();
        //2.定义不需要拦截的请求路径
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };

        //3.判断本次请求是否需要处理
        boolean check = check(urls, uri);
        //4.若不需要处理，则直接放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

        //5.1.判断登录状态,若已登录，则直接放行
        if (request.getSession().getAttribute("empId") != null){
            //获取当前登录用户的id，存放到ThreadLocal中
            long empId = (long) request.getSession().getAttribute("empId");
            BaseContext.setCurrentId(empId);
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //5.2.判断移动端用户登录状态,若已登录，则直接放行
        if (request.getSession().getAttribute("userId") != null){
            //获取当前登录用户的id，存放到ThreadLocal中
            long userId = (long) request.getSession().getAttribute("userId");
            BaseContext.setCurrentId(userId);
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //6.如果未登录则返回失败结果，通过输出流的方式响应给客户端
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls 需要放行的请求集合
     * @param uri 本次请求
     * @return
     */
    public boolean check(String[] urls,String uri){
        for (String url : urls) {
            boolean match = pathMatcher.match(url, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
